package com.ctg.itrdc.imageconsole.data.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

import com.ctg.itrdc.imageconsole.common.constants.DockerConstant;
import com.ctg.itrdc.imageconsole.data.constant.CommonConst;
import com.ctg.itrdc.imageconsole.data.dao.IDockerImageDao;
import com.ctg.itrdc.imageconsole.data.dto.DockerImageFileDTO;
import com.ctg.itrdc.imageconsole.data.entity.DockerAppImage;
import com.ctg.itrdc.imageconsole.data.entity.DockerAppType;
import com.ctg.itrdc.imageconsole.data.entity.DockerImage;
import com.ctg.itrdc.paspsdk.common.entity.PageInfo;
import com.ctg.itrdc.paspsdk.common.utils.type.StringUtils;
import com.ctg.itrdc.paspsdk.data.dao.impl.BaseDaoImpl;
import com.ctg.itrdc.paspsdk.data.entity.ClassInfoUtils;
import com.ctg.itrdc.paspsdk.data.entity.ColumnInfo;

@Component("dockerImageDao")
public class DockerImageDaoImpl extends BaseDaoImpl implements IDockerImageDao {
	
    public PageInfo<DockerImageFileDTO> jdbcFindPageInfo(Long userId, String imageName,String imageType, int currentPage, int perPageNum) { 
    	String columnsName = ClassInfoUtils.getColumnsName(DockerImage.class);
        String tableName = ClassInfoUtils.getTableName(DockerImage.class);
        StringBuilder sql = new StringBuilder(" SELECT ");
        sql.append(columnsName).append(",(SELECT COUNT(*) FROM DOCKER_IMAGE_INDEX WHERE DOCKER_IMAGE_FILE_ID = A.ID) IMAGE_INDEX_COUNT FROM ")
        .append(tableName).append(" A WHERE 1=1");
        
        List<Object> params = new ArrayList<Object>();
        
		sql.append(" AND STATE != ? ");
    	params.add(DockerConstant.DockerImageCons.REMOVE);
        if(StringUtils.isNotEmpty(imageName)) {
        	sql.append(" AND APP_NAME LIKE ? ");
        	params.add("%" +imageName+"%");
        }
        
        if(StringUtils.isNotEmpty(imageType)) {
        	sql.append(" AND NTYPE = ? ");
        	params.add(imageType);
        }
    	sql.append(" AND (CREATE_USER_ID = ? OR ISNULL(CREATE_USER_ID) )");
    	params.add(userId);
        sql.append(" ORDER BY LAST_UPDATE_TIME DESC");
        return (PageInfo<DockerImageFileDTO>)this.jdbcFindPageInfo(sql.toString(), DockerImageFileDTO.class, params, currentPage, perPageNum, true);
    }

	private StringBuilder basicSelectSql() {
		String columnsName = ClassInfoUtils.getColumnsName(DockerImage.class);
        String tableName = ClassInfoUtils.getTableName(DockerImage.class);
        StringBuilder sql = new StringBuilder(" SELECT ");
        sql.append(columnsName).append(" FROM ").append(tableName).append(" WHERE 1=1 ");
		return sql;
	}

	@Override
	public DockerImage findDockerImageFile(Long createUserId, String tenantCode,String appName,String[] statuss) {
		if(statuss==null){return null;}
		StringBuilder sql = basicSelectSql();
        List<Object> params = new ArrayList<Object>();
        
        if (createUserId != null) {
        	sql.append(" AND CREATE_USER_ID =? ");
            params.add(createUserId);
		}
        
        sql.append(" AND TENANT_CODE =? ");
        params.add(tenantCode); 
        sql.append(" AND APP_NAME =? ");
        params.add(appName); 
        sql.append(" AND STATE IN(");
        for(int i=0,len=statuss.length;i<len;i++){
        	if(i==0){
        		sql.append("?");
        	}else {
        		sql.append(",?");
			}
        	params.add(statuss[i]); 
        }
        sql.append(") ");
        List<DockerImage> list = this.jdbcFindList(sql.toString(), DockerImage.class, params);
        if (list != null && list.size() > 0) {
			return list.get(0);
		}
        return null;
	}

	@Override
	public DockerImage findDockerImageFileById(Long imageFileId) {
		StringBuilder sql = basicSelectSql();
        List<Object> params = new ArrayList<Object>();
        
        sql.append(" and DOCKER_IMAGE_FILE_ID =?");
        params.add(imageFileId); 
       
        List<DockerImage> list = this.jdbcFindList(sql.toString(), DockerImage.class, params);
        if (list != null && list.size() > 0) {
			return list.get(0);
		}
        return null;
	}

	@Override
	public List<DockerImage> findByIdStr(String idStr) {
		
		StringBuilder sql = basicSelectSql();
		List<Object> params = new ArrayList<Object>();
		
		sql.append(" AND ID IN ?");
		params.add(idStr);
		return this.jdbcFindList(sql.toString(), DockerImage.class, params);
		
	}

	@Override
	public PageInfo<DockerImageFileDTO> queryImageFileByGroupId(Long groupId, DockerImageFileDTO dockerImageFileDTO, 
			Integer currentPage, Integer perPageNum) {
		
		StringBuilder sql = new StringBuilder(" SELECT ");
		List<Object> params = new ArrayList<Object>();
		
		List<ColumnInfo> columnList = ClassInfoUtils.getColumnMap().get(DockerImage.class);
		int i = 0;
		StringBuilder columnStr = new StringBuilder();
		for(ColumnInfo ci : columnList) {
			if(i++ != 0) {
				columnStr.append(",");
			}
			columnStr.append("A.").append(ci.getColumnName());
		}
		
		String imageFileTableName = ClassInfoUtils.getTableName(DockerImage.class);
		sql.append(columnStr.toString()).append(",GROUP_CONCAT(C.APP_NAME SEPARATOR '/') AS APP_NAMES, ");
		sql.append(" B.ID AS APP_IMAGE_ID ");
		sql.append(" FROM ").append(imageFileTableName).append(" A ");
		
		String appImageTableName = ClassInfoUtils.getTableName(DockerAppImage.class);
		sql.append(" LEFT JOIN ").append(appImageTableName).append(" B ON B.DOCKER_IMAGE_FILE_ID = A.ID ");
		
		String appTypeTableName = ClassInfoUtils.getTableName(DockerAppType.class);
		sql.append(" LEFT JOIN ").append(appTypeTableName).append(" C ON C.ID = B.DOCKER_APP_TYPE_ID WHERE 1=1 ");
		
		//类型为应用镜像的才能搜索
		sql.append(" AND A.NTYPE = ").append(CommonConst.APP_TYPE_IMAGE_FILE_TYPE);
		
		if(!StringUtils.isNullOrEmpty(dockerImageFileDTO.getState())) {
			sql.append(" AND A.STATE = ? ");
			params.add(dockerImageFileDTO.getState());
		}
		
		/*if(!StringUtils.isNullOrEmpty(dockerImageFileDTO.getTenantId())) {
			sql.append(" AND A.TENANT_CODE = ? ");
			params.add(dockerImageFileDTO.getTenantId());
		}*/
		
		if(!StringUtils.isNullOrEmpty(dockerImageFileDTO.getTiteDesc())) {
			sql.append(" AND A.TITE_DESC = ? ");
			params.add(dockerImageFileDTO.getTiteDesc());
		}

		if(!StringUtils.isNullOrEmpty(dockerImageFileDTO.getStartTime())) {
			sql.append(" AND A.CREATE_TIME >= ? ");
			params.add(dockerImageFileDTO.getStartTime());
		}
		
		if(!StringUtils.isNullOrEmpty(dockerImageFileDTO.getEndTime())) {
			sql.append(" AND A.CREATE_TIME <= ? ");
			params.add(dockerImageFileDTO.getEndTime());
		}
		
		if(!StringUtils.isNullOrEmpty(groupId)) {
			sql.append(" AND C.ID = ? ");
			params.add(groupId);
		}
		
		sql.append(" GROUP BY A.ID");
		
		return (PageInfo<DockerImageFileDTO>)this.jdbcFindPageInfo(sql.toString(), 
				DockerImageFileDTO.class, params, currentPage, perPageNum, true);
	}

	@Override
	public PageInfo<DockerImageFileDTO> canSelectImageFileByGroupId(Long groupId, DockerImageFileDTO dockerImageFileDTO,
			Integer currentPage, Integer perPageNum){
		StringBuilder sql = basicSelectSql();
        List<Object> params = new ArrayList<Object>();
        
        String appImageTableName = ClassInfoUtils.getTableName(DockerAppImage.class);
        sql.append(" AND NTYPE = ").append(CommonConst.APP_TYPE_IMAGE_FILE_TYPE);
        sql.append(" AND ID NOT IN (SELECT DOCKER_IMAGE_FILE_ID FROM ").append(appImageTableName);
        sql.append(" WHERE DOCKER_APP_TYPE_ID = ? )");
        params.add(groupId);
		return (PageInfo<DockerImageFileDTO>)this.jdbcFindPageInfo(sql.toString(), 
				DockerImageFileDTO.class, params, currentPage, perPageNum, true);
	}

	// by pshizh
	@Override
	public DockerImage selectById(Long id) 
	{
		DockerImage dockerImageFile = new DockerImage();
		dockerImageFile.setId(id);
		return super.selectByPrimaryKey(dockerImageFile);
	}

	// by pshizh
	@Override
	public DockerImage selectByAppName(String appName) {
		DockerImage imageFile = new DockerImage();
		imageFile.setImageName(appName);
		List<DockerImage> imageFiles = super.selectByExample(imageFile);
		if(imageFiles.size() != 1)
			throw new RuntimeException(String.format("Error : selecting docker_image_file by appName %s returns %d record", appName, imageFiles.size()));
		return imageFiles.get(0);
	}

	// by pshizh
	@Override
	public List<DockerImage> selectByCreateUserId(Long createUserId) {
		DockerImage imageFile = new DockerImage();
		imageFile.setCreateUserId(createUserId);
		return super.selectByExample(imageFile);
	}

	@Override
	public List<DockerImage> selectByNtype(String ntype) {
		DockerImage imageFile = new DockerImage();
		imageFile.setImageType(ntype);
		return super.selectByExample(imageFile);
	}	

	/*
	 * @param appName 	required = false
	 */
	@Override
	public PageInfo<DockerImageFileDTO> selectByCreateUserIdAndFilterByAppNameInPageInfo(Long userId, String appName,
			Integer currentPage, Integer perPageNum) {
		String sql = "select * from docker_image_index where create_user_id = ?";
		List<Object> params = new ArrayList<>();
		params.add(userId);
		if(null != appName) {
			sql = sql + " and app_name like ?";
			params.add("%" + appName +"%");
		}
		return super.jdbcFindPageInfo(sql, DockerImageFileDTO.class, params, currentPage, perPageNum);
	}

	/*
	 * @param appName 	required = false
	 */
	@Override
	public PageInfo<DockerImageFileDTO> selectByCreateUserIdAndNtypeAndFilterByAppNameInPageInfo(Long createUserId, String ntype, 
			String appName, Integer page, Integer pageSize) {
		String sql = "select * from docker_image_index where create_user_id = ? and ntype = ?";
		List<Object> params = new ArrayList<>();
		params.add(createUserId);
		params.add(ntype);
		if(null != appName) {
			sql = sql + " and app_name like ?";
			params.add("%" + appName +"%");
		}
		return super.jdbcFindPageInfo(sql, DockerImageFileDTO.class, params, page, pageSize);
	}

	

	
	
	
}
